package cn.hpclub.server.controller.admin;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.ext.render.excel.PoiRender;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.model.SalesPromotion;
import cn.hpclub.server.service.ActivityCityBusinessReportService;
import cn.hpclub.server.util.InterfaceUtil;

public class ActivityCityBusinessReportController extends BaseAdminController<SalesPromotion>{
    private static Logger logger = LoggerFactory.getLogger(ActivityCityBusinessReportController.class);

    public void list(){
        initMonthList();
        // 搜索字段
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        if(isProvinceAccount()){
            setAttr("is_province_account", "1");
        } else{
            setAttr("is_province_account", "0");
        }

        // 统计制定日期的活跃度，默认今天
        String selectDate = getSelectDate(searchInfo);
        String selectMonth = getSelectMonth(searchInfo);
        ActivityCityBusinessReportService service = ActivityCityBusinessReportService.service;
        final List<Record> dayReport = getDayReport(selectDate, service);
        setAttr("dayCityList", dayReport);
        final String monthReportTitle = getMonthReportTitle(selectMonth);
        setAttr("monthTitle", monthReportTitle);
        final List<Record> monthReport = getMonthReport(selectDate, selectMonth, service);
        setAttr("cityMonthList", monthReport);
        setAttrs(searchInfo);
        if("1".equals(getPara("isExport"))){
            export(dayReport, monthReport, monthReportTitle, selectDate);
        } else{
            render("/admin/activity_city_business_report.tpl");
        }
    }

    private void export(List<Record> dayReport, List<Record> monthReport, String monthReportTitle, String selectDate){
        initMonthList();
        // 统计制定日期的活跃度，默认今天
        List<Record> list = new ArrayList<Record>();
        for(int i = 0; i < dayReport.size(); i++){
            final Record dayRecord = dayReport.get(i);
            final Record monthRecord = monthReport.get(i);
            final Record record = new Record();
            record.set("day_org_name", dayRecord.getStr("DisplayName"));
            record.set("day_cnt20", getValue(dayRecord.getLong("cnt20")));
            record.set("day_cnt30", getValue(dayRecord.getLong("cnt30")));
            record.set("month_org_name", monthRecord.getStr("DisplayName"));
            record.set("month_cnt20", getValue(monthRecord.getLong("cnt20")));
            record.set("month_cnt30", getValue(monthRecord.getLong("cnt30")));
            list.add(record);
        }

        final String[] headesExport = { "机构", "办理5笔指定业务及以上人数(" + selectDate + ")", "销售4G+终端人数(" + selectDate + ")",
                "机构", "办理5笔指定业务及以上人数(按月统计" + monthReportTitle + ")", "销售4G+终端人数(按月统计" + monthReportTitle + ")" };
        PoiRender excel = PoiRender.me(list);
        final String[] columnsExport = { "day_org_name", "day_cnt20", "day_cnt30", "month_org_name", "month_cnt20",
                "month_cnt30" };
        render(excel.sheetName("预约信息报表").headers(headesExport).columns(columnsExport).fileName(generateFileName()));
    }

    private Object getValue(Object obj){
        if(null == obj){
            return "--";
        } else{
            return obj;
        }
    }

    String generateFileName(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HHmmssSSS");
        String curTime = sdf.format(date);
        String fileName = "赢话费报表-" + curTime + ".xlsx";
        // System.out.println("excel file name:" + fileName);
        try{
            return new String(fileName.getBytes("gbk"), "iso8859-1");
        }
        catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }
        return fileName;
    }

    private String getMonthReportTitle(String selectMonth){
        String startDate = selectMonth + "-01";
        String monthTitle = "";
        if(getThisMonth().equals(selectMonth)){
            if(getToday().equals(startDate)){
                // 本月第一天不统计本月数据
                monthTitle = selectMonth + "(暂无本月数据)";
            } else{
                monthTitle = selectMonth + "-01" + "至" + getYesterday();

            }
        } else{
            monthTitle = selectMonth;
        }
        return monthTitle;
    }

    private List<Record> getMonthReport(String selectDate, String selectMonth,
            ActivityCityBusinessReportService service){
        String startDate = selectMonth + "-01";
        String endDate = "";
        if(getThisMonth().equals(selectMonth)){
            if(getToday().equals(startDate)){
                // 本月第一天不统计本月数据
            } else{
                endDate = getYesterday();
            }
        } else{
            endDate = getEndDateOfMonth(startDate);
        }
        List<Record> cityMonthRecords = null;
        if(isProvinceAccount()){
            cityMonthRecords = service.getCityReport(startDate, endDate);
        } else if(isCityAccount()){
            cityMonthRecords = service.getAreaReport("" + InterfaceUtil.getOrgId(), startDate, endDate);
        } else{
            cityMonthRecords = new ArrayList<Record>();
        }
        return cityMonthRecords;
    }

    private List<Record> getDayReport(String selectDate, ActivityCityBusinessReportService service){
        List<Record> cityRecords = null;
        if(isProvinceAccount()){
            cityRecords = service.getCityReport(selectDate, selectDate);
        } else if(isCityAccount()){
            cityRecords = service.getAreaReport("" + InterfaceUtil.getOrgId(), selectDate, selectDate);
        } else{
            cityRecords = new ArrayList<Record>();
        }
        return cityRecords;
    }

    public void listArea(){
        String cityCode = getPara("city_code");
        if(StrKit.isBlank(cityCode)){
            cityCode = String.valueOf(InterfaceUtil.getOrgId());
        }
        setAttr("cityCode", cityCode);
        initMonthList();
        // 搜索字段
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        // 统计制定日期的活跃度，默认今天
        String selectDate = getSelectDate(searchInfo);
        String selectMonth = getSelectMonth(searchInfo);

        ActivityCityBusinessReportService service = ActivityCityBusinessReportService.service;
        final List<Record> cityRecords = service.getAreaReport(cityCode, selectDate, selectDate);
        setAttr("dayCityList", cityRecords);

        String monthTitle = selectMonth;
        String startDate = selectMonth + "-01";
        List<Record> cityMonthRecords = null;
        String endDate = "";
        if(getThisMonth().equals(selectMonth)){
            if(getToday().equals(startDate)){
                // 本月第一天不统计本月数据
                monthTitle = selectMonth + "(暂无本月数据)";
            } else{
                monthTitle = selectMonth + "-01" + "至" + getYesterday();
                endDate = getYesterday();
            }
        } else{
            monthTitle = selectMonth;
            endDate = getEndDateOfMonth(startDate);
        }
        cityMonthRecords = service.getAreaReport(cityCode, startDate, endDate);
        setAttr("cityMonthList", cityMonthRecords);
        setAttr("monthTitle", monthTitle);
        setAttrs(searchInfo);
        if("1".equals(getPara("isExport"))){
            export(cityRecords, cityMonthRecords, monthTitle, selectDate);
        } else{
            render("/admin/activity_area_business_report.tpl");
        }
    }

    private String getSelectDate(ConcurrentHashMap<String, String> searchInfo){
        String selectDate = searchInfo.get("select_date");
        if(selectDate == null){
            selectDate = getPara("select_date");
            if(StrKit.isBlank(selectDate)){
                selectDate = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
            }
            searchInfo.put("select_date", selectDate);
        }
        return selectDate;
    }

    private String getSelectMonth(ConcurrentHashMap<String, String> searchInfo){
        String selectMonth = searchInfo.get("select_month");
        if(StrKit.isBlank(selectMonth)){
            selectMonth = getPara("select_month");
            if(StrKit.isBlank(selectMonth)){
                selectMonth = DateFormatUtils.format(new Date(), "yyyy-MM");
            }
            searchInfo.put("select_month", selectMonth);
        }
        return selectMonth;
    }

    private boolean isProvinceAccount(){
        int provinceId = InterfaceUtil.getIdTop();
        int userOrgId = InterfaceUtil.getOrgId();
        return userOrgId == provinceId;
    }

    private boolean isCityAccount(){
        int accountOrgId = InterfaceUtil.getOrgId();
        return InterfaceUtil.isCityLevelOrg(accountOrgId);
    }

    private String getThisMonth(){
        DateFormat f = new SimpleDateFormat("yyyy-MM");
        return f.format(new Date());
    }

    private String getToday(){
        DateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        return f.format(new Date());
    }

    private String getYesterday(){
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, -1);
        return f.format(calendar.getTime());
    }

    private void initMonthList(){
        List<String> list = new ArrayList<String>();
        DateFormat f = new SimpleDateFormat("yyyy-MM");
        Date startDate = null;
        final String configMonth = getConfigValue("ACT_SALES_DAILY_COUNT_START_DATE");
        try{
            startDate = f.parse(configMonth + "-01");
        }
        catch(ParseException e){
            e.printStackTrace();
        }

        Calendar c = Calendar.getInstance();
        c.setTime(startDate);
        String month = f.format(c.getTime());
        String currentMonth = f.format(new Date());
        System.out.println("currentMonth:" + currentMonth);
        System.out.println("month:" + month);
        while(month.compareTo(currentMonth) <= 0){
            list.add(f.format(c.getTime()));
            c.add(Calendar.MONTH, 1);
            month = f.format(c.getTime());
        }
        setAttr("monthList", list);
    }

    private String getConfigValue(String key){
        String sql = "SELECT * FROM sys_code_value WHERE code=? AND is_deleted=0";
        Record record = Db.findFirst(sql, key);
        if(record == null){
            return "";
        }
        return record.getStr("value");
    }

    private String getEndDateOfMonth(String startDate){
        String endDate = "";
        try{
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
            Date date = f.parse(startDate);
            calendar.setTime(date);
            calendar.add(Calendar.MONTH, 1);
            calendar.set(Calendar.DATE, 1);
            calendar.add(Calendar.DATE, -1);
            endDate = f.format(calendar.getTime());
        }
        catch(ParseException e){
            e.printStackTrace();
        }
        return endDate;
    }

}
